package com.kp.ai.controller;

import com.kp.ai.service.CarBookingService;
import com.kp.ai.service.function.CarBookingFunction;
import com.kp.ai.entity.CarType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.List;

/**
 * 业务接口
 */
@RestController
@CrossOrigin(origins = {"http://localhost:5173", "http://127.0.0.1:5173"}, allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
@RequestMapping("/api")
public class BookingController {
	private static final Logger logger = LoggerFactory.getLogger(BookingController.class);
	private final CarBookingService carBookingService;

	public BookingController(CarBookingService carBookingService) {
		this.carBookingService = carBookingService;
	}

	@GetMapping("/bookings")
	public Page<CarBookingFunction.BookingDetails> getBookings(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) {
		return carBookingService.getCarOrders(PageRequest.of(page, size));
	}

	@GetMapping("/car-types")
	public List<CarType> getCarTypes() {
		return carBookingService.getAllCarTypes();
	}

	@PutMapping("/bookings/{bookingNumber}")
	public ResponseEntity<?> updateBooking(@PathVariable String bookingNumber, @RequestBody CarBookingFunction.ChangeBookingDatesRequest request) {
		try {
			logger.info("Attempting to update booking: {}", bookingNumber);
			carBookingService.changeBooking(
				request.bookingNumber(),
				request.name(),
				request.date(),
				request.from(),
				request.to(),
				request.carTypeId()
			);
			return ResponseEntity.ok().build();
		} catch (IllegalArgumentException e) {
			logger.error("Failed to update booking: {}", e.getMessage());
			return ResponseEntity.badRequest().body(e.getMessage());
		} catch (Exception e) {
			logger.error("Unexpected error while updating booking: ", e);
			return ResponseEntity.internalServerError().body("修改订单时发生错误");
		}
	}

	@PostMapping("/bookings/{bookingNumber}/cancel")
	public ResponseEntity<?> cancelBooking(@PathVariable String bookingNumber) {
		try {
			logger.info("Attempting to cancel booking: {}", bookingNumber);
			carBookingService.cancelBooking(bookingNumber);
			return ResponseEntity.ok().build();
		} catch (IllegalArgumentException e) {
			logger.error("Failed to cancel booking: {}", e.getMessage());
			return ResponseEntity.badRequest().body(e.getMessage());
		} catch (Exception e) {
			logger.error("Unexpected error while canceling booking: ", e);
			return ResponseEntity.internalServerError().body("取消订单时发生错误");
		}
	}
}
